package com.murphy.security.token;

import com.alibaba.fastjson.JSONObject;
import com.murphy.security.cache.Cache;
import com.murphy.security.dto.UserDTO;
import com.murphy.security.exception.CacheException;
import io.jsonwebtoken.Claims;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * token相关操作
 * @author dongsufeng
 * @version 4.0
 * @date 2019/12/2 2:49 PM
 */
@Component
@Log4j2
public class TokenService {

    @Autowired
    private Cache cacheManager;


    /**
     * 生成令牌
     *
     * @param
     * @return .
     */
    public String generateToken(Authentication authentication) {
		UserDTO userDTO = (UserDTO)authentication.getPrincipal();
		StringBuilder stringBuilder = new StringBuilder("username");
		stringBuilder.append(userDTO.getUsername()).append("password");
		stringBuilder.append(userDTO.getPassword()).append("userId");
		stringBuilder.append(userDTO.getUserId()).append(System.currentTimeMillis());
		return DigestUtils.md5DigestAsHex(stringBuilder.toString().getBytes());
	}
	/**
	 * 验证令牌是否时间有效
	 *
	 * @param token 令牌
	 * @return 是否有效
	 */
	public String validateToken(String token) {
		try {
			if (StringUtils.isEmpty(token)){
				return null;
			}
			Object o = cacheManager.get(token);
			if (o != null) {
				cacheManager.put(token, o.toString(), 7, TimeUnit.DAYS);
				cacheManager.put(o.toString(), token, 7, TimeUnit.DAYS);
				return o.toString();
			}
		} catch (Exception e) {
			log.error("", e);
		}
		return null;
	}
}
